function varargout = mythenread(varargin)
% MYTHENREAD Read data in MYTHEN file
%       MYTHENREAD(FILE) returns the 2D data of mythenscan.
%       [DATA,X] = MYTHENREAD(FILE) returns 2D data of mythenscan and list
%           of scan variable X.
%
% Zhang Jiang 
% $revision 1.0 $  $Date: 2009/04/06 $

file = varargin{1};
np = 1280;                                   % number of channels of Mythen
nline = 25;                                    % number of data points per line in the file
pix = (1:np)';
x = [];
gid = [];
[fid,message] = fopen(file,'r');        
while feof(fid) == 0
    scanline = fgetl(fid);
    if length(scanline) >= 3 && strcmp(scanline(1:4),'#PN ')
        x_str = scanline(5:end);
        scanline = fgetl(fid);
        x = [x, str2num(scanline(5:end))];
        while ~strcmp(scanline(1:3),'@A ')
            scanline = fgetl(fid);
        end
        line_gid = str2num(scanline(4:end-1));
        for ii=1:floor((np-nline)/nline)
            line_gid = [line_gid,fscanf(fid,'%g',[1,nline])];
            scanline = fgetl(fid);
        end;
        line_gid = [line_gid,fscanf(fid,'%g',[1,mod(np-nline,nline)])];
        gid = [gid;line_gid];        
    end
end;
fclose(fid);  
gid = gid';
varargout{1} = gid;
if nargout == 2
    varargout{2} = x;
end
return;

